package engine.systems.audio.audio
{
	import engine.GameEngine;
	import engine.classes.enumerations.SystemPriority;
	import engine.systems.update.GameSystem;
	import engine.utils.Command;
	
	import flash.media.Sound;
	import flash.utils.Dictionary;
	
	public class AudioSystem extends GameSystem
	{
		//Dictionary of Sound instances.
		private var cache:Dictionary = new Dictionary();
		
		public function AudioSystem(nodeClass:Class, nodeUpdateFunction:Function, nodeAddedFunction:Function=null, nodeRemovedFunction:Function=null)
		{
			super(AudioNode, updateNode);
			
			this.priority = SystemPriority.AUDIO;
		}
		
		private function updateNode(node:AudioNode, time:Number):void
		{
			var audio:Audio = node.audio;
			
			this.toPlay(audio);
		}
		
		private function toPlay(audio:Audio):void
		{
			while(audio._toPlay.length > 0)
			{
				var data:AudioData = audio._toPlay.pop();
				
				var sound:Sound = this.cache[data.url];
				if(!sound)
				{
					GameEngine.loadFile(Audio.AUDIO_PATH + data.url, Command.create(this.soundLoaded, data));
				}
				else
				{
					this.soundLoaded(sound, data);
				}
			}
		}
		
		private function soundLoaded(sound:Sound, data:AudioData):void
		{
			var numLoops:int = data.loop
			data.channel = sound.play(
		}
	}
}